<template>
  <div class="edit-popup">
    <popup
      ref="popupRef"
      :title="popupTitle"
      :async="true"
      width="550px"
      @confirm="handleSubmit"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="120px"
      >
        <el-form-item label="连续签到天数" prop="days" >
          <el-input v-model="formData.days" placeholder="请输入连续签到天数" />
        </el-form-item>
        <el-form-item label="赠送礼品券数量" prop="balance2" >
          <el-input v-model="formData.balance2" placeholder="请输入赠送礼品券数量" />
        </el-form-item>
		<el-form-item label="赠送优惠券">
		    <el-radio-group v-model="formData.coupon_id">
				<template v-for="item in gradeList">
					<el-radio :label="item.id">{{item.name}}</el-radio>
				</template>
		    </el-radio-group>
		</el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import { userCouponList} from "@/api/consumer";
import {addContinuousReward,detailContinuousReward,editContinuousReward} from "@/api/consumer";
import Popup from "@/components/popup/index.vue";
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const mode = ref("add");
const popupTitle = computed(() => {
  return mode.value == "edit" ? "编辑签到奖励" : "新增签到奖励";
});
const formData = reactive({
  days:'',
  balance2:'',
  coupon_id:0,
  roll_id:''
});
const gradeList = ref([]);

userCouponList().then((res) => {
    gradeList.value = res.list.map((_res: any) => {
        return {id: _res.id, name: _res.name}
    })
});

const setFormDatas = (data:any[]) => {
  for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
          formData[key] = data[key]
      }
  }
};
	
const coupon_state = [
	{
		id: 1,
		name: '积分'
	},
	{
		id: 2,
		name: '优惠券'
	},
	{
		id: 3,
		name: '礼品券'
	},
];


const open = (type = "add") => {
  mode.value = type;
  popupRef.value?.open();
};

const getDetail = async (id:string) => {
  const data = await detailContinuousReward({
    roll_id: id,
  });
  formData.roll_id =id
  setFormDatas(data.info);
};

const handleClose = () => {
  emit("close");
};

defineExpose({
  open,
  getDetail,
});
//提交
const handleSubmit = async () => {
	// formData.rank_id = formData.id
  await formRef.value?.validate();
  mode.value == "edit"? await editContinuousReward(formData):await addContinuousReward(formData)
  popupRef.value?.close();
  emit("success");
};
</script>
